package com.siqi.hr.system.common.controller;

import com.alibaba.fastjson.JSON;
import com.siqi.hr.common.Constants;
import com.siqi.hr.common.utils.Const;
import com.siqi.hr.common.utils.TableConstant;
import com.siqi.hr.system.common.enums.FieldEditPageEnum;
import com.siqi.hr.system.common.enums.FieldPosition;
import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.common.model.filter.QueryDataEntity;
import com.siqi.hr.system.common.sql.STable;
import com.siqi.hr.system.common.utils.QueryDataUtil;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.entity.FieldRecord;
import com.siqi.hr.system.common.service.CommonOperationService;
import com.siqi.hr.system.custom.entity.Query;
import com.siqi.hr.system.custom.service.*;
import com.siqi.hr.system.organization.entity.Employee;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.*;

/**
 * 处理公共操作方法通用控制器
 * @version 2016-08-18
 * @author xiaoxiumei
 * @since JDK1.6.0_12
 */
@Controller
@RequestMapping("CommonOperation")
public class CommonOperationController {

	@Autowired
	private CommonOperationService commonOperationService;
	@Autowired
	private EntityRecordService entityRecordService;
	@Autowired
	private EntityOperationService entityOperationService;
	@Autowired
	private FieldEmployeeService fieldEmployeeService;
	@Autowired
	private QueryService queryService;

	/**
	 * 用户布局、过滤条件设置
	 * @author xiagq 2016-08-29
	 * @param
	 * @return
	 */
	@RequestMapping(value = "fieldEmployeeLayout")
	public ModelAndView fieldEmployeeLayout(HttpServletRequest request, HttpSession session){
		Employee employee = (Employee) session.getAttribute("emp");
		//得到实体id
		Integer entityId = ServletRequestUtils.getIntParameter(request, "entityId", 0);
		//得到自己布局或系统布局过滤条件标识(true:系统设置的布局或过滤条件，false:自己设置的布局或过滤条件)
		boolean isDefault = ServletRequestUtils.getBooleanParameter(request,"isDefault",false);
		String positionval = request.getParameter("position").toString();
		FieldPosition position = positionval.equals("List") ? FieldPosition.List : FieldPosition.Filter;

		// 获得实体列表/过滤条件字段
		List<FieldRecord> allFieldList = commonOperationService.queryAllEntityLayoutField(entityId,position);

		// 获取用户设置的布局或过滤条件
		List<FieldRecord> showFieldList = new ArrayList<FieldRecord>();
		String empId = employee.getId();
		//如果是后台布局管理中设计视图布局、过滤条件
		if( isDefault ){
			showFieldList = commonOperationService.querySysSetEntityLayoutField(entityId, position);
		}else{//如果是前台布局管理中设计视图布局、过滤条件
			showFieldList = commonOperationService.queryEmpSetEntityLayoutField(empId, entityId, position);
		}
		// 获得影藏字段
		List<FieldRecord> hideFieldList = new ArrayList<FieldRecord>();
		for (FieldRecord field : allFieldList) {
			if(!showFieldList.contains(field)){
				hideFieldList.add(field);
			}
		}

		ModelAndView mav = new ModelAndView();
		mav.addObject("entityId", entityId);
		mav.addObject("position", positionval);
		mav.addObject("employeeId", empId);
		mav.addObject("isDefault",isDefault);
		mav.addObject("hideFieldList", hideFieldList);
		mav.addObject("showFieldList", showFieldList);
		mav.setViewName("common/layout/field_emp_setting");
		return mav;
	}

	/**
	 * 保存用户布局、过滤条件设置
	 * @author xiagq 2016-08-29
	 * @return
	 */
	@RequestMapping(value = "saveFieldEmployeeLayout")
	@ResponseBody
	public Map<String,Object> saveFieldEmployeeLayout(HttpServletRequest request, HttpSession session){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//判断是后台布局管理中设计视图布局、过滤条件，还是前台（true：后台也就是默认，false：前台）
		boolean isDefault = ServletRequestUtils.getBooleanParameter(request,"isDefault",false);
		//显示字段
		String sortFields = request.getParameter("sortFields").toString();
		List<FieldRecord> fieldList = new ArrayList<FieldRecord>();
		if( StringUtils.isNotEmpty(sortFields) ){
			JSONArray json = JSONArray.fromObject(sortFields);
			fieldList = (List<FieldRecord>)JSONArray.toCollection(json, FieldRecord.class);
		}
		//所属实体
		int entityId = ServletRequestUtils.getIntParameter(request,"entityId",0);
		//布局位置
		String positionval = ServletRequestUtils.getStringParameter(request,"position","List");
		FieldPosition position = positionval.equals("List") ? FieldPosition.List: FieldPosition.Filter;
		//员工为空时：设置默认布局
		String employeeId = request.getParameter("employeeId").toString();
		try {
			commonOperationService.saveFieldEmployeeLayout(employeeId, entityId, position, fieldList,isDefault);
			resultMap.put("result","success");
		} catch (Exception e) {
			resultMap.put("result","error");
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 获取弹出框查询头内容
	 * @param request
	 * @param printWriter
	 * @param isTable      是否是弹窗(true:是，false:列表数据)
	 */
	@RequestMapping(value = "searchCondition")
	public void searchCondition(HttpServletRequest request, PrintWriter printWriter,Boolean isTable){
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		String tableNumberStr = request.getParameter("tableCode");
		int tableNumber = 0;
		//String searchCondition = "";
		Map<String,Object> columnMap = new HashMap<String,Object>();
		List<FieldRecord> fieldsList = new ArrayList<FieldRecord>(); //获取字段信息
		try {
			tableNumber = Integer.parseInt(tableNumberStr);
			//searchCondition = fieldEmployeeService.queryEmployeeFilter(emp, tableNumber, isTable);
			columnMap = fieldEmployeeService.getEntityColumns(emp,tableNumber, true,true);
			fieldsList = fieldEmployeeService.getFieldRecordList(emp,tableNumber);
		}catch (Exception e){
			e.printStackTrace();
		}

		QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
		queryData.setEmployee(emp);
		queryData.setTableCode(tableNumber);
		queryData.setFields(columnMap.get("fields").toString().split(","));
		queryData.setUsepager(true);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			resultMap =  commonOperationService.queryCustomObjectAll(queryData);
			if(tableNumber == TableConstant.ROLE_TCODE && !emp.getId().equals(Constants.ROOTEMPID)){//若不是admin登录，则不能给成员设置admin角色
				List<Map<String,Object>> oldRows = (List<Map<String,Object>>)resultMap.get("rows");
				List<Map<String,Object>> newRows = new ArrayList<Map<String,Object>>();
				int totalCount = 0;
				for (Map<String,Object> oldRow: oldRows) {
					if(!oldRow.get("id").equals(Constants.ROOTROLEID)){
						newRows.add(oldRow);
						totalCount += 1;
					}
				}
				resultMap.put("total",totalCount);
				resultMap.put("rows",newRows);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String ,Object > objectMap = new HashMap<String ,Object >();
		//objectMap.put("searchCondition",searchCondition);
		objectMap.put("resultMap",resultMap);
		objectMap.put("fieldsList",fieldsList);
		objectMap.put("fields",columnMap.get("fields"));
		objectMap.put("isTable", isTable);
		printWriter.print(JSON.toJSONString(objectMap));
	}

	/**
	 * bootstrap表格数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "querySearch")
	@ResponseBody
	public Map<String,Object> querySearch(HttpServletRequest request){
		//得到需要过滤数据的id(xiaogq)
		String searchIds = request.getParameter("searchIds");
		QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
		queryData.setUsepager(true);
		queryData.setBootstrapQuery(true);
		if(StringUtils.isNotBlank(searchIds)){
			queryData.setSearchIds(searchIds);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			resultMap =  commonOperationService.queryCustomObjectAll(queryData);
			if(queryData.getTableCode().intValue() == TableConstant.ROLE_TCODE && !queryData.getEmployee().getId().equals(Constants.ROOTEMPID)){
				List<Map<String,Object>> oldRows = (List<Map<String,Object>>)resultMap.get("rows");
				List<Map<String,Object>> newRows = new ArrayList<Map<String,Object>>();
				int totalCount = 0;
				for (Map<String,Object> oldRow: oldRows) {
					if(!oldRow.get("id").equals(Constants.ROOTROLEID)){
						newRows.add(oldRow);
						totalCount += 1;
					}
				}
				resultMap.put("total",totalCount);
				resultMap.put("rows",newRows);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 初始化客户化实体列表页面
	 * @param request
	 * @param entityId   实体id
	 * @param isTable    是否是弹窗(true:是，false:列表数据)
	 * @return
	 */
	@RequestMapping(value = "initCustomer", method = RequestMethod.GET)
	public ModelAndView initCustomer(HttpServletRequest request, Integer entityId,Boolean isTable) throws Exception{
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		EntityRecord entity = entityRecordService.queryEntityRecordById(entityId);

		//获取头部列表操作按钮
		List<EntityOperation> listButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), entityId,OperationEnum.showList);
		//定制查询
		List<Query> queryList = this.queryService.queryListShowCustQueryList(emp.getId(), entityId);
		//获取用户过滤条件
		String condition = fieldEmployeeService.queryEmployeeFilter(emp, entityId,isTable);
		//获取实体头部
		Map<String,Object> columnMap = fieldEmployeeService.getEntityColumns(emp,entityId, true,true);

		ModelAndView andView = new ModelAndView();
		andView.addObject("listButtons", listButtons);
		andView.addObject("condition", condition);
		andView.addObject("columns", columnMap.get("columns"));
		andView.addObject("fields", columnMap.get("fields"));
		andView.addObject("queryList", queryList);
		//是否显示定制搜索按钮功能(true:显示，false:不显示)
		andView.addObject("showdzSearch", true);
		andView.addObject("entity", entity);
		andView.addObject("isTable", isTable);
		andView.setViewName("common/custom/custom_list");
		return andView;
	}

	/**
	 * 查询客户化实体列表 (主要用于框架测试 demo)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryCustomerAll")
	@ResponseBody
	public Map<String,Object> queryEmployeeAll(Integer tableCode, HttpServletRequest request) throws Exception{
		//获取搜索条件、当前登录用户、客户化实体以及分页数据信息
		QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
		//设置列表数据分页查询
		queryData.setUsepager(true);
		//获取列头操作按钮
		List<EntityOperation> colButtons = entityOperationService.queryEntityOperationByHere(queryData.getEmployee().getRole(), tableCode, OperationEnum.showColumn);
		Map<String, Object> resultMap =  commonOperationService.queryCustomObjectAll(queryData);
		//处理可登录模块字段
		List<Map<String, Object>> datasResult = (List<Map<String, Object>>) resultMap.get(Const.ROWS);
		for(Map<String, Object> map : datasResult){
			//添加列表列前操作按钮
			map.put("operation", colButtons);
		}
		return resultMap;
	}

	/**
	 * 添加页面初始化
	 * @param entityId 实体id
	 * @return
	 */
	@RequestMapping(value = "customAddInit", method = RequestMethod.GET)
	public ModelAndView customAddInit(HttpServletRequest request,int entityId) throws Exception{
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		//EntityRecord entity = entityRecordService.queryEntityRecordById(entityId);
		//根据实体id、角色id获取添加，编辑页显示字段
		List<FieldRecord> fields = commonOperationService.getEditOrViewPageFields(entityId, emp.getRole().getId(),FieldEditPageEnum.hidden_edit);
		List<Map<String, Object>> fieldRecords = commonOperationService.getEditPageFields(entityId,fields);
		ModelAndView andView = new ModelAndView();
		//andView.addObject("entity", entity);
		andView.addObject("entityId", entityId);
		andView.addObject("fieldRecords", fieldRecords);
		andView.addObject("saveUrl", "CommonOperation/customSave.do");
		andView.setViewName("common/custom/custom_add");
		return andView;
	}

	/**
	 * 添加自定义实体保存方法
	 * @author         xiaogq
	 * @param entityId    实体信息对象id
	 * @Return ModelAndView
	 */
	@RequestMapping(value="customSave", method = RequestMethod.POST)
	@ResponseBody
	public String customSave(HttpServletRequest request, int entityId, DefaultMultipartHttpServletRequest multipartRequest){
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		EntityRecord entity = entityRecordService.queryEntityRecordById(entityId);
		//获取前端传过来的form表单值
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
		for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
			String key = entry.getKey().toString();
			String[] value=(String[])entry.getValue();
			if(!key.equals("entityId")){
				dataMap.put(key,value[0]);
			}
		}
		JSONObject balkJson = new JSONObject();
		String id = commonOperationService.addTData(dataMap, entity, emp, multipartRequest);
		if(StringUtils.isNotBlank(id)){
			balkJson.put("success","success");
		}else{
			balkJson.put("error","error");
		}
		return balkJson.toString();
	}

	/**
	 * 修改页面初始化
	 * @param entityId 实体id
	 * @return
	 */
	@RequestMapping(value = "customEditInit", method = RequestMethod.GET)
	public ModelAndView customEditInit(int entityId, String id, HttpServletRequest request) throws Exception{
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		EntityRecord entity = new EntityRecord(entityId);
		//根据实体id、角色id获取添加，编辑页显示字段
		List<FieldRecord> fields = commonOperationService.getEditOrViewPageFields(entityId, emp.getRole().getId(),FieldEditPageEnum.hidden_edit);
		//获取在编辑页面显示字段信息
		List<Map<String, Object>> fieldRecords = commonOperationService.getEditPageFields(entityId,fields);
		//根据id获取该记录id
		Map<String, Object> map = commonOperationService.queryTDataInfoById(entityId,id,fields);
		ModelAndView andView = new ModelAndView();
		andView.addObject("entity", entity);
		andView.addObject("fieldRecords", fieldRecords);
		andView.addObject("datas", map);
		andView.addObject("saveUrl", "CommonOperation/customEdit.do");
		andView.setViewName("common/custom/custom_edit");
		return andView;
	}

	/**
	 * 修改自定义实体保存方法
	 * @author         xiaogq
	 * @param entityId    实体信息对象id
	 * @Return ModelAndView
	 */
	@RequestMapping(value="customEdit", method = RequestMethod.POST)
	@ResponseBody
	public String customEdit(HttpServletRequest request, int entityId, String id, DefaultMultipartHttpServletRequest multipartRequest){
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		EntityRecord entity = entityRecordService.queryEntityRecordById(entityId);
		//获取前端传过来的form表单值
		Map<String, String[]> parameterMap = request.getParameterMap();
		Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
		for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
			String key = entry.getKey().toString();
			String[] value = entry.getValue();
			if(!key.equals("entityId") && !key.equals("id")){
				dataMap.put(key,value[0]);
			}
		}
		JSONObject balkJson = new JSONObject();
		int counts = commonOperationService.updateTData(dataMap, entity, emp, id, multipartRequest);
		if(counts > 0){
			balkJson.put("success","success");
		}else{
			balkJson.put("error","error");
		}
		return balkJson.toString();
	}

	/**
	 * 通用数据删除
	 * @param entityId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "customDelete")
	@ResponseBody
	public JSONObject customDelete(int entityId, String id) throws Exception {
		//根据实体id获取实体对象信息
		EntityRecord entityRecord = entityRecordService.queryEntityRecordById(entityId);
		JSONObject obj = commonOperationService.deleteTData(entityRecord, id);
		return obj;
	}

	/**
	 * 通用数据停用
	 * @param entityId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "customDisable")
	@ResponseBody
	public String customDisable(int entityId,String id) throws Exception {
		commonOperationService.disableTDate(STable.TABLE_HEAD + entityId, id);
		JSONObject balkJson = new JSONObject();
		balkJson.put("success","success");
		return balkJson.toString();
	}

	/**
	 * 通用数据启用
	 * @param entityId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "customEnable")
	@ResponseBody
	public String customEnable(int entityId,String id) throws Exception {
		commonOperationService.enableTDate(STable.TABLE_HEAD + entityId, id);
		JSONObject balkJson = new JSONObject();
		balkJson.put("success","success");
		return balkJson.toString();
	}

	/**
	 * 查看页面
	 * @param entityId 实体id
	 * @return
	 */
	@RequestMapping(value = "customView", method = RequestMethod.GET)
	public ModelAndView customView(int entityId, String id, HttpServletRequest request) throws Exception{
		Employee emp = (Employee) request.getSession().getAttribute("emp");
		EntityRecord entity = entityRecordService.queryEntityRecordById(entityId);
		List<EntityOperation> listButtons = new ArrayList<EntityOperation>();
		//获取详情页操作按钮
		List<EntityOperation> viewButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), entityId, OperationEnum.showView);
		for(EntityOperation operation : viewButtons){
			if(operation.getIcon().endsWith("-edit")){
				operation.setIcon("image/common/operation/oper_UPDATE.png");
			}else if(operation.getIcon().endsWith("-trash")){
				operation.setIcon("image/common/operation/oper_DELETE.png");
			}
			listButtons.add(operation);
		}
		Map<String, Object> resultDataMap = commonOperationService.getViewPageFields(id,entityId, emp.getRole().getId(),FieldEditPageEnum.hidden_show);
		//获取字段信息
		List<FieldRecord> fieldRecords = (List<FieldRecord>) resultDataMap.get("fieldRecord");
		//获取字段值
		Map<String,Object> datas = (Map<String, Object>) resultDataMap.get("datas");
		ModelAndView andView = new ModelAndView();
		andView.addObject("id",id);
		andView.addObject("entity", entity);
		andView.addObject("listButtons", listButtons);
		andView.addObject("fieldRecords", fieldRecords);
		andView.addObject("datas", datas);
		andView.setViewName("common/custom/custom_view");
		return andView;
	}
}